package cn.xawl.gulimall.cart.interceptor;

import cn.xawl.common.constant.CartConstant;
import cn.xawl.common.constant.MemberConstant;
import cn.xawl.common.vo.MemberVo;
import cn.xawl.gulimall.cart.vo.UserInfoTo;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author lh
 * @create 2020-11-02 13:45
 *
 * 让第一次使用购物车的用户保存一个user-key的cookie信息（无论是否登录）
 *
 **/
public class CartTempUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberVo member = (MemberVo) session.getAttribute(MemberConstant.LOGIN_USER);
        if (member != null) {
            //当前用户已登录
            userInfoTo.setUserId(member.getId());
        }
        //未登录用户，分配一个临时用户
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //如果cookie中已经有临时用户
                if (cookie.getName().equals(CartConstant.CART_TEMP_USER_KEY)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //没有临时用户，我们需要创建一个临时用户，此次请求响应时让浏览器保存一个cookie
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        //没有临时用户，我们需要创建一个临时用户，此次请求响应时让浏览器保存一个cookie
        if (!userInfoTo.getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.CART_TEMP_USER_KEY, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.CART_TEMP_USER_EXPIRE_TIME);
            response.addCookie(cookie);
        }

    }
}
